#include"mybuffer.h"
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>

#define FILEPERMISSION 0666

_FILE* _fopen(const char* filename,const char* flag)
{
  int fd = -1;
  int fl = 0;
  if(strcmp(flag,"w") == 0)
  {
    fl = (O_WRONLY|O_TRUNC|O_CREAT);
    fd = open(filename,fl,FILEPERMISSION);
  }
  else if(strcmp(flag,"r") == 0)
  {
    fl = (O_RDONLY);
    fd = open(filename,fl);
  }
  else if(strcmp(flag ,"a") == 0)
  {
    fl = (O_WRONLY|O_APPEND|O_CREAT);
    fd = open(filename,fl,FILEPERMISSION);
  }
  else
  {
    return NULL;
  }

  if(fd == -1)
  {
    return NULL;
  }

  _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
  fp->fileno = fd;
  fp->flag = FLUSH_ALL;
  fp->outpos = 0;

  return fp;
}




int _fwrite(_FILE* fp,const char* s,int size)
{
  memcpy(fp->outbuffer + fp->outpos,s,size);
  fp->outpos += size;


  if(fp->flag & FLUSH_NOW)
  {
    write(fp->fileno,fp->outbuffer,fp->outpos);
    fp->outpos = 0;
  }
  else if(fp->flag & FLUSH_LINE)
  {
    if(fp->outbuffer[fp->outpos-1] == '\n')
    {
      write(fp->fileno,fp->outbuffer,fp->outpos);
      fp->outpos = 0;
    }
  }
  else if(fp->flag & FLUSH_ALL)
  {
    if(fp->outpos == SIZE)
    {
      write(fp->fileno,fp->outbuffer,fp->outpos);
      fp->outpos = 0;
    }
  }


  return size;
}

void fflush(_FILE* fp)
{
  if(fp->outpos != 0)
  {
    write(fp->fileno,fp->outbuffer,fp->outpos);
    fp->outpos = 0;
  }
}



void _fclose(_FILE* fp)
{
  if(fp == NULL)
    return;
  fflush(fp);
  close(fp->fileno);
  free(fp);
}






